<template>
  <div class="main_box">
    <el-row class="header-row">
      <el-col>
        <div class="search_wrap">
          <el-form :inline="true" :model="searchForm" ref="searchForm">
            <el-form-item prop="userName">
              <el-input v-model="searchForm.userName" :clearable="true" placeholder="用户名"></el-input>
            </el-form-item>
            <el-form-item prop="nickName">
              <el-input v-model="searchForm.nickName" :clearable="true" placeholder="用户昵称"></el-input>
            </el-form-item>
            <el-form-item prop="phone">
              <el-input v-model="searchForm.phone" :clearable="true" placeholder="手机号"></el-input>
            </el-form-item>
            <el-form-item prop="adminRole">
              <el-select v-model="searchForm.adminRole" :clearable="true" placeholder="请选择用户角色">
                <el-option key="1" label="系统管理员" :value="1"></el-option>
                <el-option key="5" label="社区管理员" :value="5"></el-option>
                <el-option key="6" label="119管理员" :value="6"></el-option>
                <el-option key="7" label="120管理员" :value="7"></el-option>
                <el-option key="8" label="110管理员" :value="8"></el-option>
                <!-- <el-option key="10" label="业务员" :value="10"></el-option> -->
              </el-select>
            </el-form-item>
            <!--<el-form-item prop="isLogin">
                <el-select v-model="searchForm.isLogin" :clearable="true" placeholder="请选择登陆状态">
                  <el-option key="1" label="在线" value="1"></el-option>
                  <el-option key="0" label="离线" value="0"></el-option>
                </el-select>
              </el-form-item>-->
            <el-form-item prop="state">
              <el-select v-model="searchForm.state" :clearable="true" placeholder="请选择账号状态">
                <el-option key="1" label="启用" :value="1"></el-option>
                <el-option key="0" label="禁用" :value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button icon="el-icon-search" type="primary" @click="onSearch">查询</el-button>
              <el-button icon="el-icon-refresh-left" @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
      <el-col>
        <div class="opration_wrap">
          <el-tooltip content="刷新" placement="top">
            <el-button circle icon="el-icon-refresh-right" @click="reload" size="mini"></el-button>
          </el-tooltip>
          <el-button type="primary" plain icon="fa fa-plus" v-has="permissionAdd" @click="handleClickAdd()" size="mini">新增管理员</el-button>
        </div>
      </el-col>
    </el-row>
    <el-row ref="tableRow">
      <el-table :data="tableList" :fit="true">
        <el-table-column type="index" label="序号" width="80" align="center"></el-table-column>
        <el-table-column show-overflow-tooltip prop="userName" label="用户名" align="center"></el-table-column>
        <el-table-column show-overflow-tooltip prop="nickName" label="用户昵称" align="center"></el-table-column>
        <el-table-column show-overflow-tooltip prop="phone" label="手机号" align="center"></el-table-column>
        <el-table-column label="用户角色" align="center" width="150">
          <template slot-scope="scope">
            <span>
              <el-tag size="mini" :type="formatUserRoles(scope.row.adminRole)">
                {{ formatUserRole(scope.row.adminRole) }}
              </el-tag>
            </span>
          </template>
        </el-table-column>
        <!--<el-table-column label="登陆状态" align='center' width="100">
            <template slot-scope="scope">
              <span>
                <el-tag size="mini" effect="plain" :type="formatLogins(scope.row.isLogin)">
                  {{ formatLogin(scope.row.isLogin) }}
                </el-tag>
              </span>
            </template>
          </el-table-column>-->
        <el-table-column prop="sysDepartName" label="所属公司" align="center"></el-table-column>
        <!--          <el-table-column prop="businessName" label="所属商户" ></el-table-column>-->
        <el-table-column label="账号状态" align="center" width="100">
          <template slot-scope="scope">
            <span>
              <el-tag size="mini" effect="dark" :type="formatStates(scope.row.state)">
                {{ formatState(scope.row.state) }}
              </el-tag>
            </span>
          </template>
        </el-table-column>
        <!--<el-table-column prop="loginOutTime" label="上次登录退出时间" align='center'></el-table-column>
          <el-table-column prop="loginTime" label="此次登录时间" align='center'></el-table-column>-->
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-row>
              <el-button v-has="permissionCheck" @click="handleClickDetail(scope.row)" size="mini">查看</el-button>
              <el-dropdown trigger="click" size="small">
                <el-button type="primary"><i class="fa fa-list-ul"></i>更多</el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-has="permissionEdit" @click.native="handleClickEditor(scope.row)">编辑</el-dropdown-item>
                  <el-dropdown-item v-has="permissionRole" @click.native="handleClickAddRole(scope.row)">角色设置</el-dropdown-item>
                  <el-dropdown-item v-has="permissionRelationUser" @click.native="handleBRelationUser(scope.row)">批量关联用户</el-dropdown-item>
                  <el-dropdown-item v-has="permissionRelatonTenant" @click.native="handleBRelationTenant(scope.row)">批量关联租户</el-dropdown-item>
                  <el-dropdown-item v-has="permissionResetPwd" @click.native="handleClickResetPass(scope.row)">重置密码</el-dropdown-item>
                  <el-dropdown-item v-has="permissionMagRegion" @click.native="handleSetMagRegion(scope.row)">设置管理区域</el-dropdown-item>
                  <el-dropdown-item v-has="permissionUpStatus" @click.native="handleIsDisable(scope.row)">{{ scope.row.state === 0 ? '启用' : '禁用' }}</el-dropdown-item>
                  <el-dropdown-item v-has="permissionDelete" @click.native="handleClickDelete(scope.row)">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.pageNo"
        :page-sizes="[20, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, jumper, next, pager, prev"
        :total="page.pageTotal"
      ></el-pagination>
    </el-row>

    <el-dialog :visible.sync="magRegion.show" title="设置管理区域" width="fit-content" center top="4vh">
      <div>
        <div style="text-align: end">
          <el-button icon="el-icon-plus" type="success" plain size="medium" circle @click="addBtn"> </el-button>
        </div>
        <el-table :data="magRegion.list" style="width: max-content; margin-top: 20px">
          <el-table-column label="操作" width="100" align="center">
            <template slot-scope="scope">
              <el-button icon="el-icon-minus" type="danger" plain size="medium" circle @click="subBtn(scope.$index)"> </el-button>
            </template>
          </el-table-column>
          <el-table-column label="地区" width="320" align="center">
            <template slot-scope="scope">
              <Region
                :disabled="scope.row.adminVillageId ? true : false"
                style="width: 300px"
                ref="region"
                :streetValues="scope.row.streetIds"
                @regionChange="handleItemChange"
                :isChangeOnSelect="true"
                :index="scope.$index"
              ></Region>
            </template>
          </el-table-column>
          <el-table-column label="社区" width="240px" align="center">
            <template slot-scope="scope">
              <el-select :disabled="scope.row.adminVillageId ? true : false" v-model="scope.row.communityId" @focus="handleCommunityFocus(scope.row.streetIds, scope.$index)" filterable clearable>
                <el-option v-for="item in scope.row.communityList" :value="item.id" :label="item.name" :key="item.id"> </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="小区" width="240px" align="center">
            <template slot-scope="scope">
              <el-select :disabled="scope.row.adminVillageId ? true : false" v-model="scope.row.villageId" @focus="handleVillageFocus(scope.row.streetIds, scope.row.communityId, scope.$index)" filterable clearable>
                <el-option v-for="item in scope.row.villageList" :value="item.id" :label="item.name" :key="item.id"> </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="大屏" width="240px" align="center">
            <template slot-scope="scope">
              <el-select v-model="scope.row.screenIds" multiple filterable clearable @change="(val) => handleScreenSelectChange(val, scope.row, scope.$index)">
                <el-option v-for="item in screenList" :value="item.id" :label="item.name" :key="item.id"> </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column type="expand">
            <template slot-scope="scope">
              <div style="padding: 10px 20px" v-if="scope.row.screenIds.length === 0">
                <span style="font-size: 16px; width: 100%; text-align: center; font-weight: bold">清先选择绑定大屏</span>
              </div>
              <div style="padding: 10px 20px" v-else>
                <el-form :inline="true" label-width="120px">
                  <div v-for="(item, index) in bigScreenRelationList[scope.$index]" :key="index">
                    <el-form-item label="大屏名称"> {{ item.bigScreenName }} </el-form-item>
                    <el-form-item label="大屏标题">
                      <el-input v-model="item.mainTitle" />
                    </el-form-item>
                    <el-form-item label="大屏副标题">
                      <el-input style="width: 300px" v-model="item.subtitle" />
                    </el-form-item>
                  </div>
                </el-form>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div slot="footer">
        <el-button type="primary" @click="confirmSetMagRegion"> 确定 </el-button>
        <el-button @click="magRegion.show = false"> 取消 </el-button>
      </div>
    </el-dialog>

    <!-- 批量关联用户 -->
    <el-dialog title="批量关联用户" :visible.sync="relationUser.show" width="fit-content" center :close-on-click-modal="false">
      <el-row class="relation_user-top" style="margin-bottom: 14px; display: flex">
        <div style="margin-right: 20px">
          <el-input v-model="relationUser.teamName" placeholder="请输入分组名"></el-input>
          <div style="color: red; font-size: 14px">同组账号下的用户可以进行相互切换</div>
        </div>
        <div>
          <el-button type="success" icon="el-icon-plus" circle @click="relationUser.list.push($options.data().relationUser.list[0])"></el-button>
        </div>
      </el-row>
      <el-table :data="relationUser.list" max-height="500px">
        <el-table-column type="index" align="center" width="70px" label="序号"></el-table-column>
        <el-table-column label="操作" width="80px" align="center">
          <template slot-scope="{ $index }">
            <el-button type="danger" icon="el-icon-minus" circle @click="relationUser.list.splice($index, 1)"></el-button>
          </template>
        </el-table-column>
        <el-table-column align="center" width="200px" label="租户">
          <template slot-scope="{ row }" clearable filterable>
            <el-select v-model="row.tenantId" @change="handleTenantChange(row)" clearable filterable>
              <el-option v-for="item in getFilterTenantList(row.tenantId)" :value="item.value" :label="item.name" :key="item.id"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column align="center" width="400px" label="用户">
          <template slot-scope="{ row }">
            <el-select v-model="row.relationUserIds" multiple clearable filterable @click.native="handleUserFocus(row)" style="width: 300px">
              <el-option v-for="item in row.userList" :value="item.id" :label="item.name" :key="item.id"></el-option>
            </el-select>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer">
        <el-button type="primary" @click="confirmRelationUser">确定</el-button>
        <el-button @click="relationUser.show = false">取消</el-button>
      </div>
    </el-dialog>

    <!-- 批量关联租户 -->
    <el-dialog title="批量关联租户" :visible.sync="relationTenant.show" width="fit-content" center :close-on-click-modal="false">
      <el-select style="width:350px;margin:40px;50px;100px;50px" multiple v-model="relationTenant.list" placeholder="请选择租户">
        <el-option v-for="item in tenantFilterList" :value="item.value" :label="item.name" :key="item.value"></el-option>
      </el-select>
      <div slot="footer">
        <el-button type="primary" @click="confirmRelationTenant">确定</el-button>
        <el-button @click="relationTenant.show = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import * as message from '@/constants/message';
import { FORMAT_DATE_YYYY_MM_DD } from '@/constants/constants';
import ProvinceCity from '@/components/ProvinceCity';
import AuthApi from '@/api/system/auth';
import VillageApi from '@/api/address/village';
import Region from '@/components/Region';
import TenantApi from '@/api/system/tenant';
import LoginApi from '@/api/system/login';
import CommunityApi from '@/api/address/community';
import Vue from 'vue';
export default {
  name: 'AdminManagement',
  inject: ['reload'], //注入局部刷新
  data() {
    return {
      searchForm: {
        userName: '',
        nickName: '',
        phone: '',
        adminRole: '',
        state: '',
      },
      tableList: [],

      page: {
        pageNo: 1,
        pageTotal: 0,
        pageSize: 20,
      },
      permissionCheck: 'SYSTEM_MANAGER_SYS_ADMIN_LIST_SEE',
      permissionAdd: 'SYSTEM_MANAGER_SYS_ADMIN_LIST_ADD',
      permissionEdit: 'SYSTEM_MANAGER_SYS_ADMIN_LIST_EDIT',
      permissionUpStatus: 'SYSTEM_MANAGER_SYS_ADMIN_LIST_STATE',
      permissionDelete: 'SYSTEM_MANAGER_SYS_ADMIN_LIST_DELETE',
      permissionResetPwd: 'SYSTEM_MANAGER_SYS_ADMIN_LIST_RESET',
      permissionRole: 'SYSTEM_MANAGER_SYS_ADMIN_LIST_ROLE',
      permissionIsLoginApp: 'SYSTEM_MANAGER_SYS_ADMIN_LIST_IS_LOGIN_APP',
      permissionMagRegion: 'SYSTEM_MANAGER_SYS_ADMIN_LIST_MAG_REGION',
      permissionRelatonTenant: 'SYSTEM_MANAGER_SYS_ADMIN_LIST_REALTION_TENANT',
      permissionRelationUser: 'SYSTEM_MANAGER_SYS_ADMIN_LIST_REALTION_USER',
      magRegion: {
        show: false,
        list: [],
        adminId: '',
      },
      relationUser: {
        show: false,
        teamName: '',
        list: [{ tenantId: '', relationUserIds: [], userList: [] }],
      },
      relationTenant: {
        show: false,
        list: [],
      },
      tenantList: [],
      tenantFilterList: [],
      rowItem: null,
      screenList: [],
      bigScreenRelationList: [],
    };
  },
  components: {
    ProvinceCity,
    Region,
  },
  created() {
    this.init();
    window.addEventListener('keydown', this.keyDown);
  },
  activated() {
    if (this.$route.meta.keepAlive) {
      this.listTable();
    }
  },
  destroyed() {
    window.removeEventListener('keydown', this.keyDown, false);
  },
  methods: {
    init() {
      this.listTable();
      this.getTenantList();
      this.getTableHeight();
      this.fetchLargeScreenList();
    },
    // 获取大屏地址
    fetchLargeScreenList() {
      AuthApi.bigScreenList({}).then((res) => {
        const { data } = res;
        this.screenList = data;
      });
    },
    // 大屏选择change
    handleScreenSelectChange(value, row, index) {
      let mainTitle = '';
      if (row.levels === 1) mainTitle = row.provinceName;
      if (row.levels === 2) mainTitle = row.cityName;
      if (row.levels === 3) mainTitle = row.areaName;
      if (row.levels === 4) mainTitle = row.streetName;
      if (row.levels === 5) mainTitle = row.communityList[0].name;
      if (row.levels === 6) mainTitle = row.villageList[0].name;
      const { bigScreenRelationList, screenList } = this;
      const screenSubtitle = [
        { id: 1, title: '智慧消防安全数字中心' },
        { id: 2, title: '智慧居家养老看护中心' },
        { id: 3, title: '120中心报警大屏' },
      ];

      value.forEach((val) => {
        if (!bigScreenRelationList[index].find((item) => item.bigScreenId === val)) {
          bigScreenRelationList[index].push({ bigScreenId: val, bigScreenName: screenList.find((bs) => bs.id === val).name, mainTitle, subtitle: screenSubtitle.find((ss) => ss.id === val).title });
        }
      });
      Vue.set(
        bigScreenRelationList,
        index,
        bigScreenRelationList[index].filter((item) => value.includes(item.bigScreenId)),
      );
    },

    // 获取经营范围列表数据
    handleSetMagRegion(row) {
      this.bigScreenRelationList = [];
      const { magRegion } = this;
      AuthApi.listVillage({ adminId: row.adminId }).then((res) => {
        const { data } = res;
        magRegion.list = [];
        data.forEach((item) => {
          const { provinceId, cityId, areaId, streetId, villageId, provinceName, cityName, areaName, streetName, villageName, levels, adminVillageId, communityId, communityName, bigScreenRelationList } = item;
          this.bigScreenRelationList.push(bigScreenRelationList || []);
          magRegion.list.push({
            adminVillageId,
            communityList: communityId ? [{ id: communityId, name: communityName }] : [],
            communityId: communityId ? Number(communityId) : '',
            provinceId,
            cityId,
            areaId,
            screenIds: bigScreenRelationList ? bigScreenRelationList.map((i) => i.bigScreenId) : [],
            streetId: streetId || '',
            provinceName,
            cityName,
            areaName,
            streetName: streetName || '',
            levels,
            streetIds: [provinceId, cityId, areaId, streetId || '', provinceName, cityName, areaName, streetName || ''],
            villageId,
            villageList: villageId ? [{ id: villageId, name: villageName }] : [],
          });
        });
        magRegion.show = true;
        magRegion.adminId = row.adminId;
      });
    },
    addBtn() {
      this.bigScreenRelationList.push([]);
      this.magRegion.list.push({
        provinceId: '',
        cityId: '',
        areaId: '',
        streetId: '',
        villageId: [],
        levels: '',
        streetIds: [],
        villageList: [],
        communityId: '',
        communityList: [],
        screenIds: [],
      });
    },
    subBtn(index) {
      this.magRegion.list.splice(index, 1);
    },
    formatTime(row, column, cellValue) {
      return this.$Utils.formatDate(cellValue, FORMAT_DATE_YYYY_MM_DD);
    },
    formatSex(row, column, cellValue) {
      return cellValue === 1 ? '男' : '女';
    },
    formatUserRole(cellValue) {
      if (cellValue === 1) {
        return '系统管理员';
      } else if (cellValue === 5) {
        return '社区管理员';
      } else if (cellValue === 6) {
        return '119管理员';
      } else if (cellValue === 7) {
        return '120管理员';
      } else if (cellValue === 8) {
        return '110管理员';
      } else if (cellValue === 10) {
        return '业务员';
      }
    },
    formatUserRoles(cellValue) {
      if (cellValue === 1) {
        return 'success';
      } else if (cellValue === 5) {
        return 'warning';
      } else if (cellValue === 6 || cellValue === 7 || cellValue === 8) {
        return 'danger';
      } else if (cellValue === 10) {
        return 'info';
      }
    },
    formatState(cellValue) {
      if (cellValue === 0) {
        return '禁用';
      } else if (cellValue === 1) {
        return '启用';
      }
    },
    formatStates(cellValue) {
      if (cellValue === 0) {
        return 'warning';
      } else if (cellValue === 1) {
        return 'success';
      }
    },
    formatLogin(cellValue) {
      if (cellValue === 0 || cellValue === '') {
        return '离线';
      } else if (cellValue === 1) {
        return '在线';
      }
    },
    formatLogins(cellValue) {
      if (cellValue === 0) {
        return 'info';
      } else if (cellValue === 1) {
        return 'success';
      }
    },
    listTable() {
      let data = {
        pageNo: this.page.pageNo,
        pageSize: this.page.pageSize,
        userName: this.searchForm.userName,
        nickName: this.searchForm.nickName,
        phone: this.searchForm.phone,
        adminRole: this.searchForm.adminRole,
        state: this.searchForm.state,
        isLogin: this.searchForm.isLogin,
      };
      this.fetchData(data);
    },
    handleItemChange(val) {
      let region = this.magRegion.list[val.index];
      region.communityList = []; //清空社区列表
      region.communityId = ''; //清空对应的社区id
      region.villageList = []; //清空小区列表
      region.villageIds = []; //清空对应的小区id
      region.levels = ''; //每次修改都重新修改赋值层级
      region.provinceId = val.provinceId;
      region.provinceName = val.provinceName;
      region.cityId = val.cityId;
      region.cityName = val.cityName;
      region.areaId = val.areaId;
      region.areaName = val.areaName;
      region.streetId = val.streetId;
      region.streetName = val.streetName;
      region.levels = val.levels;

      if (val.provinceId) {
        region.streetIds = [val.provinceId, val.cityId, val.areaId, val.streetId];
      } else {
        region.streetIds = [];
      }

      if (val.levels == 1 || val.levels == 2) {
        // // 只选到第一级和第二级别那么就直接清空
        region.villageList = []; //清空小区列表
        region.villageId = ''; //清空对应的小区id
        // this.$refs.region.clearStreetIds();
        // this.$message.error("请至少选至三级地区");
      }
    },
    handleVillageFocus(streetIds, communityId, index) {
      const { magRegion } = this;
      // 点击小区的时候调用接口
      let levels = magRegion.list[index].levels;
      if (levels >= 3) {
        let param = {
          provinceId: streetIds[0],
          cityId: streetIds[1],
          areaId: streetIds[2],
          streetId: streetIds[3],
          communityId,
          name: '',
        };
        VillageApi.villageList(param).then((res) => {
          magRegion.list[index].villageList = res.data;
        });
      }
    },

    // 获取社区
    handleCommunityFocus(streetIds, index) {
      const { magRegion } = this;
      let region = magRegion.list[index];
      region.villageList = []; //清空小区列表
      region.villageIds = []; //清空对应的小区id
      let levels = magRegion.list[index].levels;
      if (levels >= 3) {
        let param = {
          provinceId: streetIds[0],
          cityId: streetIds[1],
          areaId: streetIds[2],
          streetId: streetIds[3],
          name: '',
        };
        CommunityApi.listIdName(param).then((res) => {
          magRegion.list[index].communityList = res.data;
        });
      }
    },
    confirmSetMagRegion() {
      const { magRegion } = this;
      magRegion.show = false;
      const params = {
        adminId: magRegion.adminId,
        adminVillage: [],
      };
      magRegion.list = magRegion.list.filter((item) => item.streetIds.length);
      magRegion.list.forEach((item, index) => {
        if (item.villageId) {
          params.adminVillage.push({
            adminVillageId: item.adminVillageId,
            provinceId: item.provinceId,
            cityId: item.cityId,
            areaId: item.areaId,
            communityId: item.communityId || '',
            communityName: item.communityId ? item.communityList[0].name : '',
            streetId: item.streetId || '',
            villageId: item.villageId,
            provinceName: item.provinceName,
            cityName: item.cityName,
            areaName: item.areaName,
            streetName: item.streetName || '',
            levels: 5,
            bigScreenRelationList: this.bigScreenRelationList[index],
            villageName: item.villageList
              .filter((n) => n.id == item.villageId)
              .map((n) => n.name)
              .join(','),
          });
        } else {
          params.adminVillage.push({
            provinceId: item.provinceId,
            adminVillageId: item.adminVillageId,
            cityId: item.cityId,
            areaId: item.areaId,
            provinceName: item.provinceName,
            cityName: item.cityName,
            areaName: item.areaName,
            streetName: item.streetName || '',
            streetId: item.streetId || '',
            levels: item.levels,
            communityId: item.communityId,
            communityName: item.communityId ? item.communityList[0].name : '',
            bigScreenRelationList: this.bigScreenRelationList[index],
          });
        }
      });
      AuthApi.setVillage(params).then(() => {
        this.$Utils.notifySuccess('设置成功');
      });
    },
    // 获取租户列表
    async getTenantList() {
      const { data } = await TenantApi.listIdName();
      this.tenantList = data || [];
      this.tenantFilterList = this.tenantList.filter((item) => item.value != this.$store.getters.tenantId);
    },

    // 获取某一行绑定的租户
    async handleBRelationTenant(row) {
      this.rowItem = row;
      const { relationTenant } = this;
      const { data } = await LoginApi.listRelationTenantData({
        userId: row.userId,
      });
      relationTenant.show = true;
      relationTenant.list = (data || []).map((item) => item.relationTenantId);
    },
    // 确定绑定租户
    async confirmRelationTenant() {
      const {
        relationTenant,
        rowItem: { userId },
      } = this;
      await this.$confirm('确定关联租户吗？', '提示', {});
      const params = {
        userId,
        list: relationTenant.list,
        teamName: relationTenant.teamName,
      };
      await LoginApi.batchSetRelationTenant(params);
      this.$Utils.notifySuccess('关联成功');
      relationTenant.show = false;
    },
    // 获取没有选择的租户列表
    getFilterTenantList(tenantId) {
      const {
        tenantList,
        relationUser: { list },
      } = this;
      return tenantList.filter((item) => !list.some((item2) => item2.tenantId === item.value) || item.value === tenantId);
    },
    // 获取绑定的用户和租户
    async handleBRelationUser(row) {
      const { relationUser } = this;
      const { data } = await LoginApi.listRelationData({ userId: row.userId });

      this.rowItem = row;
      relationUser.show = true;

      (data || []).forEach((item) => {
        item.relationUserIds = item.relationUserIds.split(',').map((item2) => Number(item2));
        const name = item.relationUserNames.split(',');
        const userList = [];
        name.forEach((item2, index) => {
          userList.push({
            id: Number(item.relationUserIds[index]),
            name: item2,
          });
        });
        this.$set(item, 'userList', userList);
      });
      relationUser.list = data;
      relationUser.teamName = data[0] ? data[0].teamName : '';
    },
    // 租户改变
    async handleTenantChange(row) {
      row.userList = [];
      row.relationUserIds = [];
    },
    // 获取用户列表
    async handleUserFocus(row) {
      const params = {
        tenantId: row.tenantId,
        userRole: 1,
        detailRole: 1,
        type: 2,
      };
      console.log(this.$store.getters.userId);
      const { data } = await LoginApi.roleInfoList(params);
      const userList = (data || []).filter((item) => item.id !== this.$store.getters.userId);
      this.$set(row, 'userList', userList);
    },
    // 确定关联用户
    async confirmRelationUser() {
      const {
        relationUser,
        rowItem: { userId },
      } = this;
      relationUser.list = relationUser.list.filter((item) => item.relationUserIds.length);
      await this.$confirm('确定关联用户吗？', '提示', {});
      const params = {
        userId,
        userIds: relationUser.list.map((item) => item.relationUserIds).flat(),
        teamName: relationUser.teamName,
      };
      await LoginApi.batchSetRelation(params);
      this.$Utils.notifySuccess('关联成功');
      relationUser.show = false;
    },
    handleSizeChange(size) {
      this.page.pageSize = size;
      this.listTable();
    },
    handleCurrentChange(val) {
      this.page.pageNo = val;
      this.listTable();
    },
    handleClickEditor({ adminId }) {
      this.$router.push({ path: '/sys/adminAdd', query: { id: adminId } });
    },
    handleClickDetail(row) {
      this.$router.push({
        path: '/sys/adminDetail',
        query: { id: row.adminId },
      });
    },
    handleClickResetPass(row) {
      this.$confirm('确定重置该用户登录密码吗？', message.TITLE_PROMPT, {}).then(() => {
        AuthApi.resetUserPwd({ userId: row.userId }).then((res) => {
          this.$Utils.notifySuccess('重置密码成功');
        });
      });
    },
    handleClickAdd() {
      this.$router.push({ path: '/sys/adminAdd' });
    },
    handleClickAddRole(row) {
      this.$router.push({ path: '/sys/userRole', query: { id: row.userId } });
    },

    handleIsDisable(row) {
      let currentState = row.state === 0 ? 1 : 0;
      let newStateName = row.state === 0 ? message.MSG_CONFIRM_ENABLE : message.MSG_CONFIRM_DISABLE;
      this.$confirm(newStateName, message.TITLE_PROMPT, {}).then(() => {
        let data = {
          userId: row.userId,
          loginType: 1,
          state: currentState,
        };
        AuthApi.updateUserState(data).then((res) => {
          row.state = currentState;
          this.$Utils.notifySuccess();
        });
      });
    },

    handleClickDelete(row) {
      this.$confirm(message.MSG_CONFIRM_DELETE, message.TITLE_PROMPT, {}).then(() => {
        let data = {
          id: row.userId,
          state: -1,
        };
        AuthApi.deleteUser(data).then((res) => {
          this.listTable();
          this.$Utils.notifySuccess();
        });
      });
    },
    fetchData(data) {
      this.$emit('show-loading', true);
      AuthApi.listAdmin(data)
        .then((res) => {
          this.tableList = res.data.list;
          this.page.pageTotal = res.data.total;
          this.$emit('show-loading', false);
        })
        .catch((error) => {
          this.$emit('show-loading', false);
        });
    },
    onSearch() {
      this.page.pageNo = 1;
      this.listTable();
    },
    resetForm() {
      this.$refs.searchForm.resetFields();
      this.onSearch();
    },
    keyDown(e) {
      //如果是回车则执行查询方法
      if (e.keyCode == 13) {
        this.onSearch();
      }
    },
    getTableHeight() {
      this.$nextTick(function () {
        this.maxHeight = window.innerHeight - this.$refs.tableRow.$el.offsetTop - 50;
        window.onresize = () => {
          this.maxHeight = window.innerHeight - this.$refs.tableRow.$el.offsetTop - 50;
        };
      });
    },
  },
};
</script>
<style lang="scss">
@import '@/assets/css/views/content.scss';
</style>
<style lang="scss" scoped>
@import '@/assets/css/views/add.scss';
</style>
